package com.alander.nexusgo.framework.file.starter.utils;

import com.alander.nexusgo.framework.file.starter.model.OssProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.UUID;

@Component
public class FileUtils {

    private final OssProperties ossProperties;

    public FileUtils(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }

    public String generateFileName(String originalFileName, String preFilePath) {
        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String prefix = StringUtils.hasText(preFilePath) ? preFilePath : "";
        if (!prefix.isEmpty() && prefix.charAt(prefix.length() - 1) != '/') {
            prefix += "/";
        }
        return prefix + datePath + "/" + UUID.randomUUID().toString().replace("-", "") +
                "_" + originalFileName;
    }

    // 确保URL带有协议头
    public String ensureProtocol(String url) {
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            return "https://" + url;
        }
        return url;
    }

    // 计算文件MD5值
    public String calculateFileMd5(MultipartFile file) throws IOException {
        try (InputStream inputStream = file.getInputStream()) {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
            }
            byte[] digest = md.digest();
            return Base64.getEncoder().encodeToString(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not available", e);
        }
    }

    // 校验文件合法性
    public void validateFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }

        long maxSize = Long.parseLong(ossProperties.getMaxFileSize());
        if (file.getSize() > maxSize) {
            throw new IllegalArgumentException("文件大小超出限制：" + maxSize + " 字节");
        }
    }
}
